import json
from math import ceil
from typing import List
import akshare as ak
import pandas
import requests
from PyQt5 import QtCore
from PyQt5.QtCore import QThread
from utils.BaseSignal import BaseSignal


class ThreadUpdateWidget(QThread, BaseSignal):
    signalWidgetRowChangeColor = QtCore.pyqtSignal(int, str)

    def __init__(self, parent=None):
        super().__init__(parent=parent)
        self.rowsPerPage = 20
        self.curPage = 0
        self.stockDF: pandas.DataFrame = pandas.DataFrame()
        self.update = True
        self.m = 0
        self.n = 0
        self.index = 3
        self.maxPage = 0
        self.selfSelect: List[str] = list()
        self.heads = ['代码', '名称', '最新价', '涨跌幅', '涨跌额', '成交量', '成交额', '振幅', '最高', '最低', '今开',
                 '昨收', '量比', '换手率', '市盈率-动态', '市净率', '总市值', '流通市值', '涨速', '5分钟涨跌',
                 '60日涨跌幅', '年初至今涨跌幅']
    def setData(self,index):
        if index == 1:
            self.index = 3
        else:
            self.index = index-1
    def run(self) -> None:
        # Init
        if self.update:
            self.stockDF = ak.stock_zh_a_spot_em().dropna().drop(columns='序号')

            #if self.index == 0:
            self.stockDF = self.stockDF.sort_values(by=self.heads[self.index], ascending=[False])  # 按照最新价降序排列
            print(self.heads[self.index], self.index)
            #elif self.index == 1:
            #    self.stockDF = self.stockDF.sort_values(by=["最新价"], ascending=[False])
            # 股票行列数
            self.m, self.n = self.stockDF.shape
            self.signalSetStockWidget.emit(self.rowsPerPage, self.n, self.stockDF.columns.tolist())
            # 最大页码数
            self.maxPage = ceil(self.m / self.rowsPerPage)

        self.signalShowPermMessage.emit(f"第{self.curPage + 1}/{self.maxPage}页")
        # 当前页的第一行在数据集中的偏移
        offset = self.curPage * self.rowsPerPage

        # 更新界面
        for i in range(self.rowsPerPage):
            for j in range(self.n):
                if self.isInterruptionRequested():
                    return
                self.signalAddStockToWidget.emit(i, j, str(self.stockDF.values[offset + i][j]))
            # 如果添加了自选，则将该行设为绿色
            if self.stockDF.values[offset + i][0] in self.selfSelect:
                self.signalWidgetRowChangeColor.emit(i, '#00ae9d')
            # 更新进度条
            self.signalUpdateProgressBar.emit((i + 1) / self.rowsPerPage * 100)
        self.signalUpdateProgressBar.emit(100)


class ThreadUpdateZhWidget(QThread, BaseSignal):
    signalUpdateWindow = QtCore.pyqtSignal(list)

    def __init__(self, parent=None):
        super(ThreadUpdateZhWidget, self).__init__(parent)
        self.data = list()
        self.headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) '
                          'Chrome/63.0.3239.132 Safari/537.36 QIHU 360SE '
        }

    def run(self) -> None:
        """
        调接口获取上证指数，深证成指
        :return:
        """
        try:
            res = requests.get(
                "https://push2.eastmoney.com/api/qt/ulist/get?fields=f12,f13,f14,f1,f2,f4,f3&secids=1.000001,"
                "0.399001&pn=1&np=1",
                headers=self.headers)
            js = json.loads(res.text)
            self.data = js['data']['diff']
            self.signalUpdateWindow.emit(self.data)
        except requests.exceptions as e:
            print(e)
